<style>
.table-title{
  margin-bottom:20px;
}
.el-icon-delete{
  color:red;
  cursor: pointer;
}
.factory-tree{
  position: absolute;
  width: 660px;
  z-index: 99;
  border: 1px solid #dadada;
  border-radius: 10px;
  padding: 20px;
  height: 340px;
  bottom: -340px;
  overflow: auto;
  background: #fff;
}
.checkList .el-checkbox+.el-checkbox,.checkList .el-checkbox{
  margin-left: 15px;
}
.toggle-list{
  margin-left:10px;
  color:#3a8ee6;
  cursor: pointer;
}
</style>
<template>
<div>
  <div class="table-title">
    <el-button type="danger" @click="addMaster" icon="el-icon-circle-plus">添加</el-button>
    <el-button>批量导入</el-button>
  </div>
  <el-table :data="tableData" border>
    <el-table-column label="操作" align="center" width="100">
      <template slot-scope="scope">
        <i class="el-icon-delete" :title="'删除'" @click="tableData.splice(scope.$index,1)"></i>
        <el-button type="text" @click="editMater(scope.$index)"><i class="el-icon-edit"></i>编辑</el-button>
      </template>
    </el-table-column>
    <el-table-column label="供货区域" align="center" prop="purOrgName"></el-table-column>
    <el-table-column label="工厂" align="center" prop="factoryName"></el-table-column>
    <el-table-column label="物料编码" align="center" prop="materialCode"></el-table-column>
    <el-table-column label="物料名称" align="center" prop="materialName"></el-table-column>
    <el-table-column label="型号/规格" align="center" prop="materialSpec"></el-table-column>
    <el-table-column label="单位" align="center" prop="stockUnit"></el-table-column>
    <el-table-column label="质保期" align="center" prop="qualityTime"></el-table-column>
    <el-table-column label="采购量" align="center" prop="planQty"></el-table-column>
    <el-table-column label="交期" align="center" prop="deliveryDate"></el-table-column>
    <el-table-column label="备注" align="center" prop="remarks"></el-table-column>
  </el-table>


  <el-dialog title="新增物料" :visible.sync="dialogFormVisible" class="dialog-form" width="800px">
    <el-form :model="addMaterData" :inline="true" :rules="rules"  label-width="100px" ref="addMaterForm">
      <el-form-item style="position:absolute;top: 40px;left: 122px;">
        <el-checkbox v-model="checked" @change="changeMater">无料号</el-checkbox>
      </el-form-item>
      <el-form-item label="工厂：" prop="showTextarea" style="width:100%" class="show-tree">
        <span @click.stop="togglePanel"><el-input v-model="addMaterData.showTextarea" readonly type="textarea" :autosize="{ minRows: 2, maxRows: 10}"></el-input></span>
        <div class="factory-tree" v-show="showTree" ref="shows">
          <div v-for="m in categoryOptions" :key="m.id">
            <div class="checkAll">
              <el-checkbox v-model="m.checkAll" @change="(val)=>{handleCheckAllChange(val,m)}">{{m.purOrgName}}</el-checkbox>
              <span v-if="!!m.factoryList.length" @click.stop="m.showList=!m.showList" class="toggle-list">{{!m.showList?'展开':'收起'}}</span>
            </div>
            <div class="checkList" v-show="m.showList">
              <el-checkbox v-for="n in m.factoryList" v-model="n.checked" :key="n.id" @change="(val)=>{handleCheckedChange(val,m,n)}">{{n.factoryNameFull}}</el-checkbox>
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="物料编码：" prop="materialId" v-if="!checked">
        <select-fac-material v-model="addMaterData.materialId" @on-selection-data="getRowData" :factoryIds="addMaterData.factoryIds"></select-fac-material>
      </el-form-item>
      <el-form-item label="物料名称：" prop="materialName">
          <el-input v-model="addMaterData.materialName" :disabled="!checked"></el-input>
      </el-form-item>
      <el-form-item label="采购单位：" prop="materialUnit" v-if="checked">
          <el-select v-model="addMaterData.materialUnit"  placeholder="请选择" filterable>
            <el-option v-for="item in utilList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="采购单位：" prop="materialUnit" v-else>
          <el-input v-model="addMaterData.materialUnit" :disabled="!checked"></el-input>
      </el-form-item>
      <el-form-item label="库存单位：" prop="stockUnit" v-if="checked">
          <el-select v-model="addMaterData.stockUnit" placeholder="请选择" filterable>
            <el-option v-for="item in utilList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="采购单位：" prop="stockUnit" v-else>
          <el-input v-model="addMaterData.stockUnit" :disabled="!checked"></el-input>
      </el-form-item>
      <el-form-item label="采购量：" prop="planQty">
          <el-input v-model="addMaterData.planQty"></el-input>
      </el-form-item>
      <el-form-item label="型号/规格：" prop="materialSpec">
          <el-input v-model="addMaterData.materialSpec"></el-input>
      </el-form-item>
      <el-form-item label="质保期：" prop="qualityTime">
          <el-input v-model="addMaterData.qualityTime"></el-input>
      </el-form-item>
      <el-form-item label="交期：" prop="deliveryDate">
          <el-date-picker
          v-model="addMaterData.deliveryDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="交期"
          :picker-options="pickeroptions">
          </el-date-picker>
      </el-form-item>
      <el-form-item label="描述：" prop="remarks" style="width:100%">
          <el-input v-model="addMaterData.remarks" type="textarea"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取消</el-button>
      <el-button type="primary" @click="insertRow">确定</el-button>
    </div>
  </el-dialog>

  <el-dialog title="编辑物料" :visible.sync="editFormVisible" class="dialog-form" width="800px">
    <el-form :model="editMaterData" :inline="true" :rules="editrules"  label-width="100px" ref="editMaterForm">
      <el-form-item label="采购量：" prop="planQty">
          <el-input v-model="editMaterData.planQty"></el-input>
      </el-form-item>
      <el-form-item label="型号/规格：" prop="materialSpec">
          <el-input v-model="editMaterData.materialSpec"></el-input>
      </el-form-item>
      <el-form-item label="质保期：" prop="qualityTime">
          <el-input v-model="editMaterData.qualityTime"></el-input>
      </el-form-item>
      <el-form-item label="交期：" prop="deliveryDate">
          <el-date-picker
          v-model="editMaterData.deliveryDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="交期"
          :picker-options="pickeroptions">
          </el-date-picker>
      </el-form-item>
      <el-form-item label="描述：" prop="remarks" style="width:100%">
          <el-input v-model="editMaterData.remarks" type="textarea"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="editFormVisible = false">取消</el-button>
      <el-button type="primary" @click="editRow">确定</el-button>
    </div>
  </el-dialog>
</div>
</template>
<script>
import SelectFacMaterial from '../components/select-facMaterial';
  export default {
    beforeDestroy () {
        this.hide()
    },
    components: {
      SelectFacMaterial
    },
    props:['tableData'],
    data() {
      return {
        showTree:false,
        categoryprops: {
            label:'purOrgName',
            value: 'id',
            children: 'factoryList'
        },
        categoryOptions: [],
        checkcategorysName:{},
        checkcategorys:[],
        checked:false,
        dialogFormVisible:false,
        purOrgOptions:[],
        utilList:[],
        addMaterData:{
          showTextarea:'',
          materialId:"",
          factoryIds:[],
          materialCode:"",
          materialName:"",
          materialSpec:"",
          materialUnit:"",
          stockUnit:"",
          qualityTime:"",
          planQty:"",
          deliveryDate:"",
          remarks:""
        },
        editFormVisible:false,
        editMaterData:{
          materialSpec:"",
          qualityTime:"",
          planQty:"",
          deliveryDate:"",
          remarks:""
        },
        editrules:{
          materialSpec:[{required: true, message: '请输入型号/规格', trigger: 'blur'}],
          qualityTime:[{required: true, message: '请输入质保期', trigger: 'blur'}],
          planQty:[{required: true, message: '请输入采购量', trigger: 'blur'}],
          deliveryDate:[{required: true, message: '请选择交期', trigger: 'change'}],
          remarks:[]
        },
        rules:{
          // purOrgId:[{required: true, message: '请选择供货区域', trigger: 'change'}],
          showTextarea:[{required: true, message: '请选择工厂', trigger: 'blur'}],
          materialCode:[{required: true, message: '请输入物料编码', trigger: 'change'}],
          materialId:[{required: true, message: '请选择物料编码', trigger: 'change'}],
          materialName:[{required: true, message: '请输入物料名称', trigger: 'blur'}],
          materialSpec:[{required: true, message: '请输入型号/规格', trigger: 'blur'}],
          stockUnit:[{required: true, message: '请选择库存单位', trigger: 'change'}],
          materialUnit:[{required: true, message: '请选择物料单位', trigger: 'change'}],
          qualityTime:[{required: true, message: '请输入质保期', trigger: 'blur'}],
          planQty:[{required: true, message: '请输入采购量', trigger: 'blur'}],
          deliveryDate:[{required: true, message: '请选择交期', trigger: 'change'}],
          remarks:[]
        },
        pickeroptions:{
          disabledDate(time) {
            return time.getTime() < Date.now()
          }
        },
      };
    },
    mounted() {
      // 获取供货区域
      this.getSelectData('get', this.lib.config.host.masterData + '/system/purOrgMgt/purOrg/getPurOrgByUserId/' + this.getCurrUserId(), {}, 'id', 'purOrgName').then((data)=>{
        this.purOrgOptions = data;
      });
      this.axios.post(this.lib.config.host.masterData + '/common/sysdictionary/getDicItems/MATERIAL_UNIT').then((res)=>{
        this.utilList=res.data;
      })
      this.axios.post(this.lib.config.host.masterData + '/system/purOrgMgt/purOrg/getPurOrgWithFactory').then((res)=>{
         this.categoryOptions=res.data.map(item=>{
           item.factoryList.forEach(val=>{
             val.checked=false;
           })
           const data={
             ...item,
             showList:false
           }
           return data;
         });
       })
       this.$nextTick(() => {
        document.querySelector('body').addEventListener('click', this.handleBodyClick);
      })
    },
    watch:{
    },
    methods: {
      togglePanel () {
          this.showTree ? this.hide() : this.show()
      },
      show () {
          this.showTree = true
          document.addEventListener('click', this.hidePanel, false)
      },
      hide () {
          this.showTree = false
          document.removeEventListener('click', this.hidePanel, false)
      },
      hidePanel (e) {
          if (!this.$refs.shows.contains(e.target)) {
              this.hide()
          }
      },
      //获取显示的字段
      getLabel(data){
        let ndata=JSON.parse(JSON.stringify(data));
        let text='';
        Object.keys(ndata).forEach(k=>{
          let first=ndata[k].text.length===1?ndata[k].text[0]:ndata[k].text[0]+':';
          ndata[k].text.splice(0,1);
          text+=`${first}${ndata[k].text.join(',')}\n`
        })
        return text
      },
      //选择区域处理
      handleCheckAllChange(val,data){
        if(val){
          this.addMaterData.factoryIds.push(data.id);
          this.checkcategorysName[data.id]={
            text:[data.purOrgName],
            ids:[data.id]
          }
        }else{
          this.addMaterData.factoryIds.splice(this.addMaterData.factoryIds.findIndex(val=>{return val===data.id}),1)
          delete this.checkcategorysName[data.id]
        }
        data.factoryList.forEach(item=>{
          item.checked=val;
          if(val){
            this.addMaterData.factoryIds.push(item.id);
            this.checkcategorysName[data.id].text.push(item.factoryName);
            this.checkcategorysName[data.id].ids.push(item.id);
          }else{
            this.addMaterData.factoryIds.splice(this.addMaterData.factoryIds.findIndex(val=>{return val===item.id}),1)
          }
        })
        this.addMaterData.showTextarea=this.getLabel(this.checkcategorysName);
        this.$refs.addMaterForm.validateField('showTextarea');
        this.resetMater();
      },
      //选择工厂处理
      handleCheckedChange(item,key,data){
        if(item){
          if(!this.checkcategorysName[key.id]){
            key.checkAll=true;
            this.checkcategorysName[key.id]={
              text:[key.purOrgName,data.factoryName],
              ids:[key.id,data.id]
            }
            this.addMaterData.factoryIds.push(...[key.id,data.id]);
          }else{
            this.checkcategorysName[key.id].text.push(data.factoryName);
            this.checkcategorysName[key.id].ids.push(data.id);
            this.addMaterData.factoryIds.push(data.id);
          }
        }else{
          this.addMaterData.factoryIds.splice(this.addMaterData.factoryIds.findIndex(val=>{return val===data.id}),1);
          this.checkcategorysName[key.id].text.splice(this.checkcategorysName[key.id].text.findIndex(val=>{return val===data.factoryName}),1);
          this.checkcategorysName[key.id].ids.splice(this.checkcategorysName[key.id].ids.findIndex(val=>{return val===data.id}),1);
        }
        if(this.checkcategorysName[key.id].text.length===1){
          key.checkAll=false;
          this.handleCheckAllChange(false,key);
        }else{
          this.addMaterData.showTextarea=this.getLabel(this.checkcategorysName);
          this.resetMater();
          this.$refs.addMaterForm.validateField('showTextarea');
        }
      },
      //新增物料
      addMaster(){
        this.addMaterData.materialId='';
        this.dialogFormVisible=true;
        this.$nextTick(()=>{
          this.resetForm('addMaterForm');
          this.resetFac();
        })
      },
      //新增重置工厂选择项
      resetFac(){
        this.addMaterData.showTextarea='';
        this.checkcategorysName={};
        this.addMaterData.factoryIds=[];
        this.categoryOptions.forEach(item=>{
          item.checkAll=false;
          item.factoryList.forEach(val=>{
            val.checked=false;
          })
          item.showList=false;
        })
      },
      //重置物料信息
      resetMater(){
        this.addMaterData.materialId = '';
        this.addMaterData.materialName = '';
        this.addMaterData.materialCode = '';
        this.addMaterData.materialUnit = '';
        this.addMaterData.stockUnit = '';
      },
      changeMater(){
        if(this.checked){
          this.resetMater();
        }
        this.resetFac();
      },
      //获取物料信息
      getRowData(data){
        this.addMaterData.materialId = data.materialId;
        this.addMaterData.materialName = data.materialName;
        this.addMaterData.materialCode = data.materialCode;
        this.addMaterData.materialUnit = data.purUnitName;
        this.addMaterData.stockUnit = data.stockUnitName;
      },
      editMater(index){
        this.editFormVisible=true;
        !!this.$refs.editMaterForm?this.resetForm('editMaterForm'):null;
        this.$nextTick(()=>{
          let data=JSON.parse(JSON.stringify(this.tableData[index]));
          this.editMaterData={...data,index:index};
        })
      },
      editRow(){
        this.$refs.editMaterForm.validate((valid) => {
          if(valid){
            this.$set(this.tableData,this.editMaterData.index,JSON.parse(JSON.stringify(this.editMaterData)));
            this.editFormVisible=false;
          }
        })
      },
      //取值
      insertRow(){
        this.$refs.addMaterForm.validate((valid) => {
          if(valid){
            let data=[];
            Object.keys(this.checkcategorysName).forEach(k=>{
              let categorys=this.checkcategorysName[k];
              data.push({
                ...this.addMaterData,
                purOrgName:categorys.text[0],
                factoryName:categorys.text.slice(1,categorys.text.length).join(','),
                factIds:categorys.ids
              })
            })
            this.tableData.push(...data);
            this.dialogFormVisible=false;
            this.$emit('radioChange','2')
          }
        })
      }
    }
  }
</script>
